package com.rainliang.project.connect.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.rainliang.project.connect.bean.ConnectBean;
import com.rainliang.project.connect.service.ConnectService;
import com.rainliang.project.connect.util.ConnectUtil;
import com.rainliang.project.connect.util.QQ_Util;
import com.rainliang.project.user.basic.bean.RegistBean;
import com.rainliang.project.user.basic.bean.UserInfo;
import com.rainliang.project.user.basic.service.UserService;
import com.rainliang.project.util.CookieUtil;
import com.rainliang.project.util.MD5Util;


public class QQController extends MultiActionController implements ConnectInterface{
	protected Log logger = LogFactory.getLog(this.getClass());
	private UserService userService;
	private ConnectService connectService;
	/**
	 * oauth2.0升级
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView login(HttpServletRequest request,HttpServletResponse response) throws Exception {
				
		String openId = CookieUtil.getCookieBean(request,ConnectUtil.TXQQ_COOKIE_DATA_KEY + "_user");
		String accessToken=CookieUtil.getCookieBean(request,ConnectUtil.TXQQ_COOKIE_DATA_KEY +"_accessToken");
		
		PrintWriter out = response.getWriter();
		
		if(accessToken == null) {
			out.print("获取accessToken  失败");
			logger.warn("----------QQ_Controller login 获取accessToken  失败 accessToken is null,");
			close_div_login(request, response);
			return null;
		}
		
		if (openId == null || openId.trim().length() == 0 || "".equals(openId)|| "null".equals(openId) || "0".equals(openId)) {
			out.print("openid==null");
			logger.warn("----------QQ_Controller login openid is null,获取accessToken="+accessToken);
			close_div_login(request, response);
			return null;
		}
		Map <String,Object> map=new HashMap<String, Object>();
		map.put("openid", openId);
		map.put("oauth_token", accessToken);
		
		ConnectBean connectBean=connectService.getByConnId(openId);
		if(connectBean!=null){
			map.put("userId", connectBean.getUserId());
			return oldlogin(request, response,map);
		}else{
			return newlogin(request, response, map);
		}
	}
	@Override
	public ModelAndView oldlogin(HttpServletRequest request,HttpServletResponse response, Map<String,Object> map)throws Exception {
		Long userId=(Long)map.get("userId");		
		UserInfo user = userService.loginById(userId);
//		HttpSessionUtil.putUser(request, user);
		return close_div_login(request, response);
	}
	@Override
	public ModelAndView newlogin(HttpServletRequest request,HttpServletResponse response, Map map)throws Exception {
		String oauth_token_access = (String) map.get("oauth_token");
		String openid = (String) map.get("openid");
		RegistBean registBean =null;
		
		registBean= QQ_Util.getUserInfo_v2(oauth_token_access, openid);
		
		if (registBean == null) {
			return close_div_login(request, response);
		}
		String loginEmail = "txqq_" + openid;
		String userName = "txqq_" + openid.substring(0, 10)+ openid.substring(20);// 用loginEmail做userName太长，数据库报错
		String password = new Random(System.currentTimeMillis()).nextInt(10000)+ "";
		registBean.setEmail(loginEmail);
		registBean.setUserName(userName);
		registBean.setPasswd(MD5Util.getMD5String(password));
		UserInfo userInfo= userService.register(registBean);

		if (userInfo == null) {
			logger.warn("-------QQ_Controller---register_temp--openid:" + openid + "注册新用户失败");
			return close_div_login(request, response);
		}

//		HttpSessionUtil.putUser(request, userInfo);

		ConnectBean connectBean=new ConnectBean(userInfo.getUserId(),openid,oauth_token_access,"","",63,0);
		connectBean.setRelation(ConnectUtil.CONN_USER_BIND_RELATION_TXQQ);
		boolean f=this.connectService.addConnUser(connectBean);//插入分表
		close_div(request, response);
		return null;
	}	

	public ModelAndView close_div(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Pragrma", "no-cache");
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();

			String nextUrl = "";
							
			out.println("<script>");
			out.println("window.opener=null;");
			out.println("window.close();");
			out.println("window.location.href='/';");
			out.println("</script>");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public ModelAndView close_div_login(HttpServletRequest request,HttpServletResponse response) {
		try {
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Pragrma", "no-cache");
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();

			String nextUrl = "";
							
			out.println("<script>");
			out.println("window.opener=null;");
			out.println("window.close();");
			out.println("window.location.href='/';");
			out.println("</script>");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	/*
	*//**
	 * 已有豆丁账户，绑定微博
	 * 
	 * @param request
	 * @param response
	 * @return
	 *//*
	public ModelAndView bindold(HttpServletRequest request,HttpServletResponse response) {
		try {
			UserInfo_Home base_uHome = (UserInfo_Home) HttpSessionUtil.get(request);
			if (base_uHome == null) {
				return new ModelAndView("redirect:/");
			}
			int isbind = base_uHome.is_binding();
			String txqq_userid = base_uHome.getTxqq_uid();
			long userid_tmp = base_uHome.getUser_id();
			if ( txqq_userid == null || "".equals(txqq_userid)|| "0".equals(txqq_userid) || "null".equals(txqq_userid)) {
				return new ModelAndView("redirect:/");
			}

			String username = request.getParameter("username");
			String password = request.getParameter("password");
			LoginBean loginBean = new LoginBean();
			loginBean.setUsername(username);
			loginBean.setPassword(password);
			UserInfo_Home userInfoHome = userService.getUserInfo_homeByLoginBean(loginBean, response);
			if (userInfoHome != null && userInfoHome.getWrong_type() != null) {
				userInfoHome = null;
			}
			if (userInfoHome != null) {
				if (txqq_userid == null || txqq_userid.equals("0")) {
					return new ModelAndView("redirect:/");
				}
				//进入绑定
//				logger.warn("----QQ用户绑定豆丁，修改conn_txqq以及conn_relation表：userid_tmp="+userid_tmp+"userid="+userInfoHome.getUser_id());
				int hu_re=this.userService.binding_connUser(userInfoHome.getUser_id(),userid_tmp,txqq_userid, RenRenUtil.CONN_USER_TYPE[1]);				
				if(hu_re==1){						
					//设置conn域
					userInfoHome=this.userService.setConnField(userInfoHome);
					
					CookieUtil.saveCookie(userInfoHome, response);

					XMemcachedUtil.remove(MemcachedKeyUtil.USERINFOKEY+ userInfoHome.getUser_id());
					HttpSessionUtil.put(request, userInfoHome);
					//将临时账户的删除状态置为1
					userService.updateUserInfo(DocinFinalVar.ueser_up_deletedFlag, Long.parseLong(userid_tmp+""), "1");
					//统计qq绑定已有豆丁账户
					VstateUtil.setConnect_Operate(0, userInfoHome.getUser_id(), 2, 19,0l);
					//导数据放Queue
					MailQueueUtil.setConnBindQueue(userInfoHome.getUser_id(), RenRenUtil.CONN_USER_TYPE[1],userid_tmp);
					
					//更新用户属性
					CookieUtil.connBindDisploseUserAction(request, userInfoHome.getUser_id(), userInfoHome.getUserAction(), base_uHome.getUserAction());
					request.setAttribute("sucess", "绑定成功");
				}
				String fn = request.getParameter("fn");
				if (fn != null && fn.equals("1")) {
					try {
						PrintWriter out = response.getWriter();
						response.setContentType("text/html;charset=UTF-8");
						response.setHeader("Cache-Control", "no-store");
						response.setHeader("Pragrma", "no-cache");
						out.println("<script>");
						if(hu_re==-1){
							out.println("window.parent.showhasbind("+RenRenUtil.CONN_USER_TYPE[1]+");");			
						}else{
							out.println("window.parent.back_close_binding();");
							out.println("window.parent.closeDocinBind();");				
						}						
						out.println("</script>");
					} catch (Exception ex) {
						logger.error(ex.getMessage(), ex);
					}
					return null;
				}
			} else {
				request.setAttribute("error", "登录失败");
				String fn = request.getParameter("fn");
				if (fn != null && fn.equals("1")) {
					return null;
				}
			}

		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
		return new ModelAndView("redirect:/app/my/docin/event");
	}

	*//**
	 * 注册新用户并绑定QQ微博 (改成修改临时用户)
	 * 
	 * @param request
	 * @param response
	 * @return
	 *//*
	public ModelAndView bindnew(HttpServletRequest request,HttpServletResponse response) {
		try {
			String loginEmail = request.getParameter("login_email_new");
			String username = request.getParameter("regloginname_new");
			String password = request.getParameter("password_new");
			if (loginEmail == null || loginEmail.trim().length() == 0) {
				loginEmail = request.getParameter("login_email");
			}
			if (username == null || username.trim().length() == 0) {
				username = request.getParameter("login_name");
			}
			if (password == null || password.trim().length() == 0) {
				password = request.getParameter("password");
			}
			if(loginEmail == null || loginEmail.trim().length() == 0 || username == null || username.trim().length() == 0 || password == null || password.trim().length() == 0){
				return new ModelAndView("redirect:/");
			}
			boolean check_email = userService.checkLoginEmail(loginEmail.trim());
			if (check_email == false) {
				return new ModelAndView("redirect:/");
			}
			boolean check_name = userService.checkLoginName(username);
			if (check_name == false) {
				return new ModelAndView("redirect:/");
			
			}
			UserInfo_Home u_Home = (UserInfo_Home) HttpSessionUtil.get(request);
			if (u_Home == null) {
				return new ModelAndView("redirect:/");
			}
			long userId = u_Home.getUser_id();
			String txqq_userid = u_Home.getTxqq_uid();
			if (txqq_userid == null || "".equals(txqq_userid)|| "0".equals(txqq_userid) || "null".equals(txqq_userid)) {
				return new ModelAndView("redirect:/");
			}
		
			if (userId > 0) {
				// 2、修改临时账户的用户邮箱、用户名及密码
				ConnectBean cBean=new ConnectBean();
				cBean.setLogin_email(loginEmail);
				cBean.setOld_login_email(u_Home.getLogin_email());
				cBean.setUser_name(username);
				cBean.setOld_user_name(u_Home.getUserName());
				cBean.setPasswd(password);
				cBean.setUserId(userId);
				boolean b = userService.bindNewUser(cBean);
				if (b) {
					//更新分表的操作
					this.userService.update_connUser(userId, null, RenRenUtil.CONN_USER_TYPE[1]);
					u_Home.setLogin_email(loginEmail);
					u_Home.setUserName(username);
					u_Home.setUser_password(password);
					HttpSessionUtil.put(request, u_Home);
					//统计qq绑定新注册账户
					VstateUtil.setConnect_Operate(0, u_Home.getUser_id(), 2, 20,0l);
					String fn = request.getParameter("fn");
					if (fn != null && fn.equals("1")) {
						PrintWriter out = response.getWriter();
						response.setContentType("text/html;charset=UTF-8");
						response.setHeader("Cache-Control", "no-store");
						response.setHeader("Pragrma", "no-cache");
						out.println("<script>");
						out.println("window.parent.back_close_binding();");
						out.println("window.parent.closeDocinBind();");
						out.println("</script>");
						return null;
					}
				}
			}
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
		return new ModelAndView("redirect:/app/my/docin/event");// 返回到绑定页
	}
	
	public String downImg(String url, String path) {
		String fileName = "";
		try {
			String filepostfix = ".jpg";
			fileName = System.currentTimeMillis() + filepostfix;
			FileUtils.copyURLToFile(new URL(url), new File(path + "/"
					+ fileName));
		} catch (Exception ex) {
			fileName = "";
			logger.error("QQ photo downerror, " + ex.getMessage() + " , "
							+ url);
		} finally {

		}
		return fileName;
	}

	public QQController() {
		super();
	}

	public QQController(Object delegate) {
		super(delegate);
	}*/
	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	public ConnectService getConnectService() {
		return connectService;
	}
	public void setConnectService(ConnectService connectService) {
		this.connectService = connectService;
	}
	
}
